#!/usr/bin/env python
# -*- coding: UTF-8 -*-
from flask import Flask,request,render_template ,jsonify,redirect,abort,Response,url_for

from datetime import datetime
from werkzeug import secure_filename
import os,sys
import json
from flask_login import LoginManager,login_required,login_user,logout_user,current_user,UserMixin
import pymysql
from exts import db
import config
from models import *
import logging

pymysql.install_as_MySQLdb()

UPLOAD_FOLDER = 'mystatic'
ALLOWED_EXTENSIONS = set(['txt', 'pdf', 'png', 'jpg', 'jpeg', 'gif'])

app = Flask(__name__, static_folder='mystatic', static_url_path='')
app.config.from_object(config)
db.init_app(app)
login_manager = LoginManager()
login_manager.login_view = "login"
login_manager.init_app(app)
# @app.route('/')
# def hello_world():isLogin
#     return render_template('deviceid.html')

# silly user model
class User(UserMixin):
    
    def __init__(self, id):
        self.id = id
        self.name = "远芳"
        self.password = self.name + "_secret"
        
    def __repr__(self):
        return "%d/%s/%s" % (self.id, self.name, self.password)

@login_manager.user_loader
def load_user(user_id):
    u = User(user_id)
    u.name = "众富"
    return User(user_id)

# handle login failed
@app.errorhandler(401)
def page_not_found(e):
    # return Response('<p>Login failed</p>')
    error = 'Invalid username/password'
    a = {"code":0,"error":error}
    return json.dumps(a)

# @app.route('/login', methods=['GET', 'POST'])
# def login():
#     # Here we use a class of some kind to represent and validate our
#     # client-side form data. For example, WTForms is a library that will
#     # handle this for us, and we use a custom LoginForm to validate.
#     form = LoginForm()
#     if form.validate_on_submit():
#         # Login and validate the user.
#         # user should be an instance of your `User` class
#         login_user(user)

#         flask.flash('Logged in successfully.')

#         next = flask.request.args.get('next')
#         # is_safe_url should check if the url is safe for redirects.
#         # See http://flask.pocoo.org/snippets/62/ for an example.
#         if not is_safe_url(next):
#             return flask.abort(400)

#         return flask.redirect(next or flask.url_for('index'))
#     return flask.render_template('login.html', form=form)
# somewhere to login
@app.route("/user-login", methods=["GET", "POST"])
def login():
  
    if request.method == 'POST':
        username = request.form['username']
        password = request.form['password']        
        if username == "yuanfang" and password == "123456":
            id = 0
            user = User(id)
            login_user(user)
            # return redirect(request.args.get("next"))
            # return redirect(url_for('home'))
            a = {"code":200}
       
            return json.dumps(a)
        else:
            return abort(401)
    else:
        # return redirect(url_for('/denglu'))
        return render_template('user-login.htm')


@app.route('/user-register')
def register():
    return render_template('user-register.htm')

###处理用户注册
@app.route('/user-mreg')
def doReg():
    return render_template('index.htm')

@app.route('/agency')
def agencyList():
    return render_template('agency-list.html')

##我要理财
@app.route('/invest.htm')
def invest():
    return render_template('invest.htm')
##安全保障
@app.route('/list-8-1.html')
def security():
    return render_template('list-8-1.html')
##收益计算
@app.route('/list-14-1.html')
def income():
    return render_template('list-14-1.html')

##关于我们
@app.route('/list-2-1.html')
def about():
    return render_template('list-2-1.html')

@app.route('/list-5-1.html')
def callus():
    return render_template('list-5-1.html')

@app.route('/list-8-1.html')
def callu8():
    return render_template('list-8-1.html')

@app.route('/list-12-1.html')
def callus12():
    return render_template('list-12-1.html')

@app.route('/list-14-1.html')
def callus14():
    return render_template('list-14-1.html')

@app.route('/list-22-1.html')
def callus22():
    return render_template('list-22-1.html')

@app.route('/list-33-1.html')
def callus33():
    return render_template('list-33-1.html')

@app.route('/list-34-1.html')
def callus34():
    return render_template('list-34-1.html')

@app.route('/show-36-27-1.html')
def show3627():
    return render_template('show-36-27-1.html')



@app.route('/show-36-30-1.html')
def show3630():
    return render_template('show-36-30-1.html')


@app.route('/show-36-31-1.html')
def show3631():
    return render_template('show-36-31-1.html')


@app.route('/show-36-32-1.html')
def show3632():
    return render_template('show-36-32-1.html')


@app.route('/show-36-33-1.html')
def show3633():
    return render_template('show-36-33-1.html')

@app.route('/show-37-34-1.html')
def show3734():
    return render_template('show-37-34-1.html')
@app.route('/show-37-35-1.html')
def show3635():
    return render_template('show-37-35-1.html')

@app.route('/show-37-36-1.html')
def show3736():
    return render_template('show-37-36-1.html')
@app.route('/show-37-38-1.html')
def show3738():
    return render_template('show-37-38-1.html')

@app.route('/show-38-37-1.html')
def show3837():
    return render_template('show-38-37-1.html')

@app.route('/show-38-39-1.html')
def show3839():
    return render_template('show-38-39-1.html')


@app.route('/show-38-40-1.html')
def show3840():
    return render_template('show-38-40-1.html')

@app.route('/show-38-41-1.html')
def show3841():
    return render_template('show-38-41-1.html')



##关于我们
@app.route('/user-login.htm')
def userLogin():
    return render_template('user-login.htm')



@app.route('/')
#@login_required
def hello_world():
    # return redirect(url_for('home'))
    return render_template('index.htm')

@app.route('/index.htm')
#@login_required
def index():
    # return redirect(url_for('home'))
    return render_template('index.htm')

@app.route('/<username>.html')
@login_required
def show_user(username):
    # print(username);
    # pass
    if username=='index' or username=='order-add':
        return render_template(username+'.html');
    elif username=='order-list':
        result = db.session.query(Order).all()
        return render_template('order-list.html',devicecheck=result,orderCount=len(result))
    else :
        pass
    
def convert_to_dicts(objs):
    '''把对象列表转换为字典列表'''
    obj_arr = []
     
    for o in objs:
        #把Object对象转换成Dict对象
        dict1 = {}
        dict1.update(o.__dict__)
        obj_arr.append(dict1)
     
    return obj_arrf

@app.route('/query-order',methods=['GET', 'POST'])
def queryOrder():
    if request.method == 'GET':
        result = db.session.query(Order).all()
        obj_arr = []
     
        for o in result:
            #把Object对象转换成Dict对象
            obj_arr.append(o.toDict())
        
        return json.dumps(obj_arr,ensure_ascii=False);

@app.route('/add-order',methods=['GET', 'POST'])
def addOrder():
    if request.method == 'POST':
        dv = Order(str(request.form['title']),
        str(request.form['rihuali']),
        str(request.form['touziqixian']),
        str(request.form['qitoujine']),
        str(request.form['xiangmuguimo']),
        str(request.form['desc']))
        dv.save()
        return 'Submit success!'
    else: return 'wait submit...'

@app.route('/denglu')
def denglu():
    return render_template('login.html')

@login_required
@app.route('/home')
def home():
    return render_template('index.htm')

@app.route("/logout")
@login_required
def logout():
    logout_user()
    return redirect(url_for('login'))

@app.route('/addcheckwithdevice/<deviceidd>',methods=['GET','POST'])
def add_check_with_device(deviceidd):
    dc = DeviceCheck("","","","","","","","","")
    return render_template('addcheck.html',devicecheck = dc,deviceid=deviceidd)

@app.route('/addcheck/<id>',methods=['GET','POST'])
def add_check(id):
    dc = db.session.query(DeviceCheck).filter(DeviceCheck.id==id).first()
    deviceidd = dc.deviceid
    return render_template('addcheck.html',devicecheck = dc,deviceid=deviceidd)

@app.route('/qualitycheck/<id>')
def quality_check(id):
    result = db.session.query(Device).filter(Device.deviceid==id).first()
    if result==None:
        return render_template('nodevice.html',deviceid = id)
    else:
        dc = db.session.query(DeviceCheck).filter(DeviceCheck.deviceid==id).all()
        return render_template('deviceid.html',device=result,devicecheck=dc)

# @app.route('/login', methods=['POST', 'GET'])
# def login():
#     error = None
#     if request.method == 'POST':
#         u = request.form['username']
#         p = request.form['password']
#         if u == "yuanfang" and p == "123456":
#             a = {"code":200}
#             user = User()
#             user.id = u
#             flask_login.login_user(user)
#             resp = make_response(render_template('index.html', name=username))
#             resp.set_cookie('username', u)
#             return redirect(url_for('denglu'))
#             error = 'Invalid username/password'
#             a = {"code":0,"error":error}
#             return json.dumps(a)
#         else:
#             error = 'Invalid username/password'
#             return {"code":0,"error":error}
#     else :
#         return render_template('login.html')
# @app.route('/login', methods=['GET', 'POST'])
# def login():
#     # Here we use a class of some kind to represent and validate our
#     # client-side form data. For example, WTForms is a library that will
#     # handle this for us, and we use a custom LoginForm to validate.
#     form = LoginForm()
#     if form.validate_on_submit():
#         # Login and validate the user.
#         # user should be an instance of your `User` class
#         login_user(user)

#         flash('Logged in successfully.')

#         next = request.args.get('next')
#         # is_safe_url should check if the url is safe for redirects.
#         # See http://flask.pocoo.org/snippets/62/ for an example.
#         if not is_safe_url(next):
#             return abort(400)

#         return redirect(next or url_for('index'))
#     return render_template('login.html', form=form)

@app.route('/add-device',methods=['GET', 'POST'])
def addDevice():
    if request.method == 'POST':

        dv = Device(str(request.form['deviceid']),
        str(request.form['devicename']),
        str(request.form['projectname']),
        str(request.form['factoryname']),
        str(request.form['devicenumber']))
        dv.save()
        return 'Submit success!'
    else: return 'wait submit...'

@app.route('/submit',methods=['GET', 'POST'])
def submit():
    if request.method == 'POST':

        dc = DeviceCheck(str(request.form['deviceid']),
        str(request.form['projectname']),
        str(request.form['devicename']),
        str(request.form['uploadpeople']),
        str(request.form['role']),
        str(request.form['uploadlongitude']),
        str(request.form['uploadlatitude']),
        str(request.form['uploadimgname']),
        str(request.form['questioninfo']))
        dc.save()
        return 'Submit success!'
    else: return 'wait submit...'

def allowed_file(filename):
    return '.' in filename and \
           filename.rsplit('.', 1)[1] in ALLOWED_EXTENSIONS

@app.route('/upload/<id>', methods=['GET', 'POST'])
def upload_file(id):
    if request.method == 'POST':
        file = request.files['file']
        if file and allowed_file(file.filename):
            filename = secure_filename(file.filename)
            file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
            a = {"code": 0,"msg": "上传完成","data": {"src": filename}}
            result = Order.query.filter(Order.id==id).first()
            print(result);
            result.setImg(filename)
            return json.dumps(a)
        else :
            a = {"code": 1,"msg": "文件不存在或者不合法","data": {"src": filename}}
            return json.dumps(a)
    else :
        a = {"code": 2,"msg": "方法不支持","data": {"src": filename}}
        return json.dumps(a)

@app.route('/delete/<id>', methods=['GET', 'POST'])
def deleteOrder(id):
    if request.method == 'POST':
        result = Order.query.filter(Order.id==id).first()
        db.session.delete(result)
        db.session.commit()
        a = {"code": 0,"msg": "删除成功"}
        return json.dumps(a)
    else :
        a = {"code": 2,"msg": "方法不支持","data": {"src": filename}}
        return json.dumps(a)

@app.route('/muilti-upload' , methods=['GET','POST'])
def muiltiUpload():
    if request.method == 'POST':
        """Handle the upload of a file."""
        print('a')

	# 这里获取绝对路径
        abpath = os.path.abspath('./static/')
        filename = ""
        for upload in request.files.getlist("file"):
            filename = upload.filename.rsplit("/")[0]
            destination = "/".join([abpath, filename])
            print ("Accept incoming file:", filename)
            print ("Save it to:", destination)
            upload.save(destination)

        return filename
    else:
        return jsonify(status='error' ,msg='OVER')
    



with app.app_context():
    db.create_all()
    db.session.commit()


if __name__ == '__main__':
    print ('中国')
    app.debug = True
    handler = logging.FileHandler('flask.log', encoding='UTF-8')
    handler.setLevel(logging.DEBUG)
    logging_format = logging.Formatter(
        '%(asctime)s - %(levelname)s - %(filename)s - %(funcName)s - %(lineno)s - %(message)s')
    handler.setFormatter(logging_format)
    app.logger.addHandler(handler)
    app.run(host='0.0.0.0')
    
